package com.bookstore.repository;

import com.bookstore.entity.Book;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

@Repository
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {
    // 基本查询方法
    List<Book> findByTitleContaining(String keyword);

    List<Book> findByCategoryId(Long categoryId);

//    List<Book> findByCategoryIdAndTitleContaining(Long categoryId, String keyword);

    // 高级查询方法
    @Query("SELECT b FROM Book b WHERE b.category.id = :categoryId AND b.stock > 0")
    List<Book> findAvailableBooksByCategory(@Param("categoryId") Long categoryId);

    @Query("SELECT b FROM Book b WHERE b.price BETWEEN :minPrice AND :maxPrice")
    List<Book> findByPriceRange(@Param("minPrice") BigDecimal minPrice, @Param("maxPrice") BigDecimal maxPrice);

    @Query("SELECT b FROM Book b WHERE b.stock < :threshold")
    List<Book> findLowStockBooks(@Param("threshold") Integer threshold);

    // 带排序的查询
    List<Book> findByCategoryIdOrderByPriceAsc(Long categoryId);

    List<Book> findByCategoryIdOrderByPriceDesc(Long categoryId);

    List<Book> findByOrderByCreatedAtDesc();

    // 添加这些方法到BookRepository接口
    Page<Book> findByCategoryId(Long categoryId, Pageable pageable);
    Page<Book> findByCategoryIdIn(List<Long> categoryIds, Pageable pageable);
    Page<Book> findAll(Pageable pageable);
}